package com.lagou.edu.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author czq
 * @date 2020/7/15 23:11
 *
 * 登录拦截器
 */
public class LoginIntercepter implements HandlerInterceptor {

    private final String ADMIN = "admin";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Object username = request.getSession().getAttribute("username");
        if (username != null && ADMIN.equals(String.valueOf(username))) {
            // 如果存在登录信息，则放行
            return true;
        }

        // 否则，将页面重定向到登录页，原有代码不执行
        response.sendRedirect(request.getContextPath() + "/login/index");
        return false;
    }
}
